package com.joinway.framework.admin.core.utils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import java.util.Properties;

import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.ui.velocity.VelocityEngineUtils;

@Service
public class VelocityProcessor {
	private final static Logger log = LoggerFactory.getLogger(VelocityProcessor.class);
	
	final static String ENCODING = "UTF-8";
	
	final static VelocityEngine velocityEngine;
	
	static{
		Properties props = new Properties();
		props.setProperty("resource.loader", "class");
		props.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
//		props.setProperty("resourceLoaderPath", "classpath:template");
		velocityEngine = new VelocityEngine(props);
	}

	public void process(String template, Map<String, Object> model, String output) throws Exception {
		/*
		 * 在这里model中的编码为GBK 
		 */
		Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output), ENCODING));
		
		VelocityEngineUtils.mergeTemplate(velocityEngine, template, ENCODING, model, writer);
		writer.close();
		
		log.debug("generated output file to {}", output);
	}

}

